<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>事件总线（发布订阅模式）</title>
</head>

<body>
    <script>
        class EventEmitter {
            constructor() {
                this.cache = {}
            }
            on(name, fn) {
                if (this.cache[name]) {
                    this.cache[name].push(fn)
                } else {
                    this.cache[name] = [fn]
                }
            }
            off(name, fn) {
                let tasks = this.cache[name]
                if (tasks) {
                    const index = tasks.findIndex(f => f === fn || f.callback === fn)
                    if (index >= 0) {
                        tasks.splice(index, 1)
                    }
                }
            }
            emit(name, once = false, ...argus) {
                if (this.cache[name]) {
                    // 创建副本，如果回调函数内继续注册相同事件,会造成死循环
                    let tasks = this.cache[name].slice()
                    for () {

                    }
                }
            }
        }
    </script>
</body>

</html>